package com.coo.tao.web.utils;

import javax.servlet.http.HttpServletRequest;

public  class HttpUtil {
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;
		// ipAddress = request.getRemoteAddr();
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
		}
		if (ipAddress != null && ipAddress.indexOf(".") == -1) {
			return null;
		} else {
			// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
			if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
																// = 15
				if (ipAddress.indexOf(",") > 0) {
					String[] temparyip = ipAddress.split(",");
					for (int i = 0; i < temparyip.length; i++) {
						if (isIPAddress(temparyip[i])
								&& temparyip[i] != "127.0.0.1"
								&& temparyip[i].substring(0, 3) != "10."
								&& temparyip[i].substring(0, 8) != "192.168."
								&& temparyip[i].substring(0, 7) != "172.16."
								&& temparyip[i].substring(0, 8) != "169.254.") {
							ipAddress = temparyip[i];
						}

					}
				}
			}
		}
		return ipAddress;
	}

	public static boolean isIPAddress(String str1) {
		if (str1 == null || str1.trim().length() < 7
				|| str1.trim().length() > 15) {
			return false;
		} else {
			return true;
		}
	}
}
